import { defineStore } from 'pinia'
import type { loginForm, UserState } from './type'
import { login, getUserInfo } from '@/api/user'
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token'
import { constantRoutes } from '@/router/routes'
// 创建登录信息仓库
const loginInfoStore = defineStore('loginInfo', {
  // 数据存放
  state: (): UserState => {
    return {
      token: GET_TOKEN() || '',
      username: '',
      avatar: '',
      menuRoutes: constantRoutes,
    }
  },
  // 异步||逻辑
  actions: {
    // 登录
    async userLogin(data: loginForm) {
      const res = await login(data)
      if (res.code === 'SUCCESS') {
        // 登录成功
        this.token = res.data.token
        // 本地存储一份
        SET_TOKEN(res.data.token)
        return true
      } else {
        return Promise.reject(res.message)
      }
    },
    // 用户信息
    async getUserInfor() {
      const res = await getUserInfo()
      if (res.code === 'SUCCESS') {
        this.username = res.data.username
        this.avatar = res.data.avatar
        return true
      } else {
        return Promise.reject(res.message)
      }
    },
    // 退出登录
    userLogout() {
      this.token = ''
      this.username = ''
      this.avatar = ''
      REMOVE_TOKEN()
    },
  },
  // getters
  getters: {},
})

export default loginInfoStore
